package com.cloudcc.cloudframe.net.async;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.IHasCallback;
import com.cloudcc.cloudframe.net.ResultCallBack;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

/**
 * Data类型(可以作为基类 重写 handlersuccess 方法) 使用的时候注意设置监听啊 监听实现ResultCallBack
 * 
 * @author seven
 * 
 * @param <T>
 */
public class BeanRequest<T> extends MyJsonHttpResponseHandler implements
		IHasCallback {

	private ResultCallBack<T> l;

	/**
	 * 设置成功监听
	 * 
	 * @param listener
	 */
	public void setResultListener(ResultCallBack<T> listener) {
		this.l = listener;
	}

	/**
	 * 获取监听
	 * 
	 * @return
	 */
	@Override
	public ResultCallBack<T> getResultListener() {
		return this.l;
	}

	@Override
	public void handleSuccess(JsonObject json, String resp) {

		ParameterizedType genericSuperclass = (ParameterizedType) this
				.getClass().getGenericSuperclass();
		Type type = genericSuperclass.getActualTypeArguments()[0];
		TypeToken<?> typeToken = TypeToken.get(type);
		JsonElement jsonElement = json.get(getUsefullNode());
		T data = null;
		try {
			data = new Gson().fromJson(jsonElement, typeToken.getType());
		} catch (JsonSyntaxException e) {
			handleFailure(new ErrorInfo(JSON_PARSER_ERROR));
			return;
		}
		if (data == null) {
			handleFailure(new ErrorInfo(JSON_PARSER_ERROR));
		} else {
			if (l != null) {
				l.onSuccess(data);
			}
		}
	}

	/**
	 * json数据的额存储节点
	 * 
	 * @return 默认是data 可以自定义
	 */
	protected String getUsefullNode() {
		return "data";
	}

	@Override
	public void handleFailure(ErrorInfo e) {
		if (l != null && e != null) {
			l.onFailure(e);
		}
	}

}
